#!/bin/bash
# etcd configure dir : /etc/etcd/
# etcd tls dir : /etc/etcd/tls
# etcd data dir : /var/lib/etcd
# health check:
# ETCDCTL_API=3 etcdctl --cacert=/etc/etcd/tls/ca.crt --cert=/etc/etcd/tls/server.crt --key=/etc/etcd/tls/server.key --endpoints="https://172.16.4.61:2379,https://172.16.4.62:2379,https://172.16.4.63:2379" endpoint health --write-out=table

. /etc/profile

etcd_tls_dir="/etc/etcd/tls"

# 计算签发时间
sign_date () {

if [ -z $YEARS ] ; then
  YEARS=100
fi
current_second=$(date +%s)
expire_second=$(date -d "${YEARS}year" +%s)
inter_seconds=$((${expire_second} - ${current_second}))
inter_days=$((${inter_seconds}/60/60/24))
}


# 生成etcd-ca的server的key和cert
generate_etcd_server () {
openssl genrsa -out ${etcd_tls_dir}/server.key 2048
openssl req -new -key ${etcd_tls_dir}/server.key  -config /tmp/server-csr.conf -out /tmp/server.csr
openssl x509 -req -in /tmp/server.csr -CA ${etcd_tls_dir}/ca.crt -CAkey ${etcd_tls_dir}/ca.key -CAcreateserial -out ${etcd_tls_dir}/server.crt -days $inter_days -extensions v3_ext -extfile /tmp/server-csr.conf
}

# 生成etcd的peer的key和cert
generate_etcd_peer () {
openssl genrsa -out ${etcd_tls_dir}/peer.key 2048
openssl req -new -key ${etcd_tls_dir}/peer.key  -config /tmp/peer-csr.conf -out /tmp/peer.csr
openssl x509 -req -in /tmp//peer.csr -CA ${etcd_tls_dir}/ca.crt -CAkey ${etcd_tls_dir}/ca.key -CAcreateserial -out ${etcd_tls_dir}/peer.crt -days $inter_days -extensions v3_ext -extfile /tmp/peer-csr.conf
}

# 生成etcd的healthcheck-client的key和cert
generate_healthcheck_client() {
openssl genrsa -out ${etcd_tls_dir}/healthcheck-client.key 2048
openssl req -new -key ${etcd_tls_dir}/healthcheck-client.key  -config /tmp/healthcheck-client-csr.conf -out /tmp/healthcheck-client.csr
openssl x509 -req -in /tmp/healthcheck-client.csr -CA ${etcd_tls_dir}/ca.crt -CAkey ${etcd_tls_dir}/ca.key -CAcreateserial -out ${etcd_tls_dir}/healthcheck-client.crt -days $inter_days -extensions v3_ext -extfile /tmp/healthcheck-client-csr.conf
}

# 生成etcd的peer的key和cert
generate_apiserver_etcd_client_client() {
openssl genrsa -out ${etcd_tls_dir}/apiserver-etcd-client.key 2048

openssl req -new -key ${etcd_tls_dir}/apiserver-etcd-client.key  -config /tmp/apiserver-etcd-client-csr.conf -out /tmp/apiserver-etcd-client.csr
openssl x509 -req -in /tmp/apiserver-etcd-client.csr -CA ${etcd_tls_dir}/ca.crt -CAkey ${etcd_tls_dir}/ca.key -CAcreateserial -out ${etcd_tls_dir}/apiserver-etcd-client.crt -days $inter_days -extensions v3_ext -extfile /tmp/apiserver-etcd-client-csr.conf
}

sign_date
generate_etcd_server
generate_etcd_peer
generate_healthcheck_client
generate_apiserver_etcd_client_client
